Skip to main content

First Missing Positive

Question

Find the smallest positive integer which is not present in a given array of integers.

Example 1
Input: [3,4,-1,1]
Output: 2

Solution

all//First Missing Positive.py


def firstMissingPositive(nums):
if not nums:
return 1

# change negative values to 1
for i in range(len(nums)):
if nums[i] <= 0:
nums[i] = 1

for i in range(len(nums)):
number = abs(nums[i])
if number < len(nums):
nums[number] = -abs(nums[number])

for i in range(1, len(nums)):
if nums[i] > 0:
return i

return len(nums)